package cn.promonkey.api.teacher.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.promonkey.core.dto.UserDto;
import cn.promonkey.core.response.ResultMsg;
import cn.promonkey.core.toolkit.QueryGenerator;
import cn.promonkey.core.toolkit.UserInfoUtils;
import cn.promonkey.api.student.entity.Student;
import cn.promonkey.api.teacher.entity.Teacher;
import cn.promonkey.api.teacher.service.TeacherService;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;

/** @author <no value> */
@Slf4j
@RestController
@RequestMapping("/teacher/")
public class TeacherController {
  final TeacherService teacherService;

  public TeacherController(TeacherService teacherService) {
    this.teacherService = teacherService;
  }

  @RequestMapping("getPage")
  public String getPage(
      Teacher teacher,
      @RequestParam(name = "page", defaultValue = "1") Integer page,
      @RequestParam(name = "size", defaultValue = "10") Integer size,
      HttpServletRequest request) {
    QueryWrapper<Teacher> queryWrapper = QueryGenerator.initQueryWrapper(teacher, request.getParameterMap());
    Page<Teacher> pageable = new Page<>(page, size);
    IPage<Teacher> pageList = teacherService.page(pageable, queryWrapper);
    return ResultMsg.success(pageList);
  }

  @RequestMapping(value = "save", method = RequestMethod.POST)
  public String save(@RequestBody Teacher teacher) {
    return ResultMsg.success(teacherService.save(teacher));
  }

  @RequestMapping(value = "edit", method = RequestMethod.POST)
  public String edit(@RequestBody Teacher teacher) {
    return ResultMsg.success(teacherService.updateById(teacher));
  }

  @RequestMapping(value = "get")
  public String get(@RequestParam(name = "id") Long id) {
    return ResultMsg.success(teacherService.getById(id));
  }

  @RequestMapping(value = "delete", method = RequestMethod.POST)
  public String delete(@RequestBody Long id) {
    return ResultMsg.success(teacherService.removeById(id));
  }
  
  @RequestMapping("upload")
  public String upload(MultipartFile file,HttpServletRequest httpServletRequest) throws SocketException, IOException {
		
	UserDto userDto = UserInfoUtils.getUserInfo();
	List<Teacher> userList = new ArrayList<>();
	List<Teacher> updList = new ArrayList<>();

	Workbook workbook = new XSSFWorkbook(file.getInputStream());
	// 如果excel的后缀是xls,说明是03版，需要用如下方法
	// Workbook workbook = new HSSFWorkbook(is);
	//读取工作簿的第一张表格
	Sheet sheet = workbook.getSheetAt(0);
	  
	for (int i = sheet.getFirstRowNum() + 1; i <= sheet.getLastRowNum(); i++) {
		Row row = sheet.getRow(i);
		Teacher temp = new Teacher();
		temp.setTeacherNum(getCellValue(row.getCell(0)));
		temp.setTeacherName(getCellValue(row.getCell(1)));
		temp.setIntroduce(getCellValue(row.getCell(2)));
		temp.setTelephone(getCellValue(row.getCell(3)));
		temp.setCollege(getCellValue(row.getCell(4)));
		temp.setDepartment(getCellValue(row.getCell(5)));
		temp.setMajor(getCellValue(row.getCell(6)));
	  	temp.setBusinessId(userDto.getBusinessId());
	  	QueryWrapper<Teacher> userWrapper = new QueryWrapper<>();
	  	userWrapper.eq("teacher_num", temp.getTeacherNum());
	  	List<Teacher> list = teacherService.list(userWrapper);
	  	if(list.size()>0) {
	  		Teacher t = list.get(0);
	  		t.setTeacherName(getCellValue(row.getCell(1)));
			t.setIntroduce(getCellValue(row.getCell(2)));
			t.setTelephone(getCellValue(row.getCell(3)));
			t.setCollege(getCellValue(row.getCell(4)));
			t.setDepartment(getCellValue(row.getCell(5)));
			t.setMajor(getCellValue(row.getCell(6)));
	  		updList.add(t);
  		
	  	}else {
	  		userList.add(temp);
	  	}
	  }
			
	  if(userList.size()>0) {
		  teacherService.saveBatch(userList);
	  }
	  if(updList.size()>0) {
		  teacherService.updateBatchById(updList);
	  }
  
	  return ResultMsg.success();
  }
  
  private String getCellValue(Cell cell) {
		if (cell == null) {
			return "";
		}
		if ("NUMERIC".equals(cell.getCellType().name())) {
			return new BigDecimal(cell.getNumericCellValue()).toString();
		} else if ("STRING".equals(cell.getCellType().name()))
			return StringUtils.trimToEmpty(cell.getStringCellValue());
		else if ("FORMULA".equals(cell.getCellType().name())) {
			return StringUtils.trimToEmpty(cell.getCellFormula());
		} else if ("BLANK".equals(cell.getCellType().name())) {
			return "";
		} else if ("BOOLEAN".equals(cell.getCellType().name())) {
			return String.valueOf(cell.getBooleanCellValue());
		} else if ("ERROR".equals(cell.getCellType().name())) {
			return "ERROR";
		} else {
			return cell.toString().trim();
		}
	}
}
